// pages/bindBankCard/bindBankCard.js
Page({
    data: {
        statusBarHeight: 0,
        // 银行选项列表
        bankOptions: [{
                id: 'ICBC',
                name: '中国工商银行'
            },
            {
                id: 'ABC',
                name: '中国农业银行'
            },
            {
                id: 'BOC',
                name: '中国银行'
            },
            {
                id: 'CCB',
                name: '中国建设银行'
            },
            {
                id: 'COMM',
                name: '中国交通银行'
            },
            {
                id: 'CMB',
                name: '招商银行'
            },
            
            {
                id: 'CIB',
                name: '兴业银行'
            },
            {
                id: 'CITIC',
                name: '中信银行'
            },
            {
                id: 'SPDB',
                name: '浦发银行'
            },
            {
                id: 'PSBC',
                name: '中国邮政储蓄银行'
            },
            {
                id: 'CEB',
                name: '中国光大银行'
            },
            {
                id: 'CMBC',
                name: '中国民生银行'
            },
            {
                id: 'PAB',
                name: '平安银行'
            },
            {
                id: 'HXB',
                name: '华夏银行'
            },
            {
                id: 'NBB',
                name: '宁波银行'
            },
            {
                id: 'JSB',
                name: '江苏银行'
            },
            {
                id: 'CGB',
                name: '广发银行'
            },
           
            {
                id: 'BOSC',
                name: '上海银行'
            },
            {
                id: 'NJB',
                name: '南京银行'
            },
           
            {
                id: 'BOB',
                name: '北京银行'
            },
            {
                id: 'HSB',
                name: '徽商银行'
            },
        ],
        selectedBank: null,
        selectedBankName: '',
        selectedBankId: '',
        showBankPicker: false,
        bankName: '', // 开户行
        cardNumber: '', // 银行卡号
        cardHolder: '', // 持卡人姓名
        idNumber: '', // 身份证号
        phone: '', // 预留手机号
        bankNameValid: false, // 开户行验证状态
        cardNumberValid: false, // 银行卡号验证状态
        cardHolderValid: false, // 持卡人姓名验证状态
        idNumberValid: false, // 身份证号验证状态
        phoneValid: false, // 手机号验证状态
        formValid: false // 表单整体验证状态
    },

    onLoad() {
        // 获取状态栏高度
        const systemInfo = wx.getSystemInfoSync();
        this.setData({
            statusBarHeight: systemInfo.statusBarHeight
        });
    },
    // 打开银行选择器
    openBankPicker() {
        this.setData({
            showBankPicker: true
        });
    },

    // 关闭银行选择器
    closeBankPicker() {
        this.setData({
            showBankPicker: false
        });
    },

    // 确认选择银行
    confirmBank(event) {
        const {
            value,
            index
        } = event.detail;
        console.log(event);
        this.setData({
            selectedBankName: value.name,
            selectedBankId: value.id,
            bankNameValid: true,
            showBankPicker: false
        });
        this.validateBankNumber(value.name)

    },

    // 开户行输入
    onBankNumberInput(e) {
        this.setData({
            bankName: e.detail.value
        });
        this.validateBankNumber(e.detail.value);
    },
    // 银行卡号输入
    onCardNumberInput(e) {
        let cardNumber = e.detail.value;
        // 格式化银行卡号，每4位加一个空格
        cardNumber = cardNumber.replace(/\D/g, '').replace(/(\d{4})(?=\d)/g, '$1 ');
        this.setData({
            cardNumber: cardNumber
        });
        this.validateCardNumber(cardNumber);
    },

    // 持卡人姓名输入
    onCardHolderInput(e) {
        this.setData({
            cardHolder: e.detail.value
        });
        this.validateCardHolder(e.detail.value);
    },

    // 身份证号输入
    onIdNumberInput(e) {
        this.setData({
            idNumber: e.detail.value
        });
        this.validateIdNumber(e.detail.value);
    },

    // 手机号输入
    onPhoneInput(e) {
        this.setData({
            phone: e.detail.value
        });
        this.validatePhone(e.detail.value);
    },
    //验证开户行
    validateBankNumber(bankName) {
        const valid = bankName.trim() !== '';
        this.setData({
            bankNameValid: valid
        });
        this.validateForm();
    },
    // 验证银行卡号
    validateCardNumber(cardNumber) {
        const value = cardNumber.replace(/\s/g, '');
        const valid = /^\d{16,19}$/.test(value);
        this.setData({
            cardNumberValid: valid
        });
        this.validateForm();
    },

    // 验证持卡人姓名
    validateCardHolder(cardHolder) {
        const valid = cardHolder.trim() !== '';
        this.setData({
            cardHolderValid: valid
        });
        this.validateForm();
    },

    // 验证身份证号
    validateIdNumber(idNumber) {
        const valid = /^\d{15}(\d{2}[0-9Xx])?$/.test(idNumber);
        this.setData({
            idNumberValid: valid
        });
        this.validateForm();
    },

    // 验证手机号
    validatePhone(phone) {
        const valid = /^1[3456789]\d{9}$/.test(phone);
        this.setData({
            phoneValid: valid
        });
        this.validateForm();
    },

    // 验证整个表单
    validateForm() {
        const {
            bankNameValid,
            cardNumberValid,
            cardHolderValid,
            idNumberValid,
            phoneValid,
        } = this.data;
        const formValid = bankNameValid && cardNumberValid && cardHolderValid
        this.setData({
            formValid: formValid
        });
    },

    // 提交绑定
    submitBind(e) {
        const {
            bankName,
            cardNumber,
            cardHolder,
            idNumber,
            phone,
            selectedBankName
        } = this.data;

        // 再次验证表单
        this.validateBankNumber(selectedBankName);
        this.validateCardNumber(cardNumber);
        this.validateCardHolder(cardHolder);
        // this.validateIdNumber(idNumber);
        // this.validatePhone(phone);

        if (!this.data.formValid) {
            wx.showToast({
                title: '请填写正确的银行卡信息',
                icon: 'none'
            });
            return;
        }

        this.setData({
            loading: true
        });

        // 调用云函数绑定银行卡
        wx.cloud.callFunction({
            name: 'bindBankCard',
            data: {
                userId: wx.getStorageSync('userInfo')._id,
                bankName: selectedBankName,
                cardNumber: cardNumber.replace(/\s/g, ''), // 移除空格
                cardHolder: cardHolder,
                // idNumber: idNumber,
                // phone: phone
            },
            success: (res) => {
                if (res.result.success) {
                    wx.showToast({
                        title: '绑定成功',
                        icon: 'success'
                    });

                    // 返回上一页
                    setTimeout(() => {
                        wx.navigateBack();
                    }, 1000);
                } else {
                    wx.showToast({
                        title: res.result.message || '绑定失败',
                        icon: 'none'
                    });
                }
            },
            fail: (err) => {
                console.error('绑定银行卡失败:', err);
                wx.showToast({
                    title: '绑定失败，请重试',
                    icon: 'none'
                });
            },
            complete: () => {
                this.setData({
                    loading: false
                });
            }
        });
    }
});